package day11.CRUD;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;

public class Demo7 {
    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        Savepoint sp = null;

        try{
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);   //start transaction

            String sql1 = "update account set money=money-100 where name='aaa'";
            st = (PreparedStatement) conn.prepareStatement(sql1);
            st.executeUpdate();

            sp = conn.setSavepoint();//在这里设置事务回滚点

            String sql2 = "update account set money=money+100 where name='bbb'";
            st = (PreparedStatement) conn.prepareStatement(sql2);
            st.executeUpdate();

            int x = 1/0;

            String sql3 = "update account set money=money+100 where name='ccc'";
            st = (PreparedStatement) conn.prepareStatement(sql3);
            st.executeUpdate();

            conn.commit();

        }catch (Exception e) {
            try {
                conn.rollback(sp);//回滚到该事务点，即该点之前的会正常执行（sql1）
                conn.commit();  //回滚了要记得提交,如果没有提交sql1将会自动回滚
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            JdbcUtils.release(conn, st, rs);
        }

    }
}
